# -*- coding: utf-8 -*-
"""
-------------------------------------------------------------------------------
File    : MqSending.py
Time    : 2023/11/21 11:06
author  : mojin
Email   : 397135766@qq.com
-------------------------------------------------------------------------------
"""

from common.logger import Logger
from MqSending.MqttReceive import MqttReceive
from SerialPort.serial_port import SerialPort
from common.yaml_handler import YAMLHandler
from common import all_path
import random
from common import qt_message as mgs
from PyQt5 import QtWidgets

class MqSending():
    def __init__(self,ui):
        self.ui=ui
        self.module_name = 'MQ'
        self.SP=SerialPort()
        self.config_info = YAMLHandler.read_yaml(all_path.configPath)
        self.MQ_connection_status=False


    def MqSending_setupUi(self):


        self.combo_ports_name = self.ui.comboBox
        list_ports_name=self.SP.get_port_list()['list_ports_name']

        #self.ui.comboBox.setCurrentText(list_ports_name[0])
        for k in list_ports_name: # 串口
            self.combo_ports_name.addItem(k)
        self.combo_ports_name.currentIndexChanged.connect(self.onIndexChanged)

        #if config_info["Serial_port"] in list_ports_name:
        self.ui.comboBox.setCurrentText(self.config_info["Serial_port"])




        self.combo_BAUD= self.ui.comboBox_2



        for i in self.config_info["BAUD"]: #波特率
            self.combo_BAUD.addItem(str(i))
        self.combo_BAUD.currentIndexChanged.connect(self.BAUD_IndexChanged)


        self.ui.comboBox_2.setCurrentText(str(self.config_info["Serial_port_BAUD"]))

        self.ui.lineEdit.setPlaceholderText("请输入服务器地址")
        self.ui.lineEdit_2.setPlaceholderText("请输入客户机标识")
        self.ui.lineEdit_7.setPlaceholderText("请输入密码")
        self.ui.lineEdit_6.setPlaceholderText("请输入用户名")
        self.ui.lineEdit_7.setText(self.config_info["Mq_pwd"])
        self.ui.lineEdit_6.setText(self.config_info["Mq_name"])
        # 设置默认值为 "Default Value"
        self.ui.lineEdit_2.setText(f"client_{random.randint(100000, 999999)}")
        self.ui.lineEdit.setText(self.config_info["Mq_address"]) # 192.168.1.202:61616


        self.ui.lineEdit_4.setText(self.config_info["Mq_topic"])
        self.ui.lineEdit_5.setText(self.config_info["TX_topic"])
        self.ui.lineEdit_3.setText(self.config_info["RX_topic"])


        self.durable_Button( False)
        self.ui.pushButton_8.setEnabled(False)
        self.ui.pushButton_5.setEnabled(False)

        self.ui.pushButton_2.clicked.connect(self.mq_connect_execute) #连接mq
        self.ui.pushButton_3.clicked.connect(self.mq_close_execute)  #断开连接mq
        self.ui.pushButton_4.clicked.connect(self.mq_send_execute)  #发送mq消息
        self.ui.pushButton_5.clicked.connect(self.mq_unsubscribe_execute)  #取消订阅接收消息
        self.ui.pushButton_6.clicked.connect(self.mq_receive_execute) #订阅接收消息
        self.ui.pushButton_17.clicked.connect(self.mq_clean_up_execute) #清除接收消息框
        self.ui.pushButton_18.clicked.connect(self.mq_clean_up_textEdit_3execute) #清除发送消息框
        self.ui.pushButton_7.clicked.connect(self.open_serial_port_execute) #打开串口端口
        self.ui.pushButton_8.clicked.connect(self.close_serial_port_execute)  # 关闭串口端口



    def durable_Button(self,status):
        self.ui.pushButton_3.setEnabled(status)
        self.ui.pushButton_4.setEnabled(status)
        #self.ui.pushButton_5.setEnabled(status)
        self.ui.pushButton_6.setEnabled(status)
        self.ui.pushButton_7.setEnabled(status)
        #self.ui.pushButton_8.setEnabled(status)
        self.ui.pushButton_17.setEnabled(status)
        self.ui.pushButton_18.setEnabled(status)

    def onIndexChanged(self, index):
        self.selected_option_ports_name = self.combo_ports_name.itemText(index)
        Logger.info(self.selected_option_ports_name)

        self.config_info['Serial_port'] = self.selected_option_ports_name
        # self.config_info['Serial_port_BAUD'] = self.selected_option_BAUD
        YAMLHandler.write_yaml(all_path.configPath, self.config_info)  # 保存到配置文件中


    def BAUD_IndexChanged(self,index):
        self.selected_option_BAUD = self.combo_BAUD.itemText(index)
        Logger.info(self.selected_option_BAUD)
        #self.config_info['Serial_port'] = prot_name
        self.config_info['Serial_port_BAUD'] = self.selected_option_BAUD
        YAMLHandler.write_yaml(all_path.configPath, self.config_info)  # 保存到配置文件中


    def mqtt_connect_status(self,dic_data):
        code=dic_data['code']
        self.MQ_connection_status = True
        if code==0:
            self.ui.pushButton.setText("已连接")
            self.ui.pushButton.setStyleSheet("color:  rgb(0, 170, 0)")
            self.durable_Button(True)

            self.MqttReceive_thread.receive_topic = self.ui.lineEdit_4.text()  # 接收消息主题
            self.MqttReceive_thread.receive_message_box = self.ui.textEdit_2  # 接收消息输入框

            if self.ui.lineEdit_4.text() != '':
                self.MqttReceive_thread.subscribe_receive_msg()
                self.ui.pushButton_5.setEnabled(True)
                self.ui.pushButton_6.setEnabled(False)





        elif code==1:
            self.MQ_connection_status = False
            self.ui.pushButton.setText('已断开')
            self.ui.pushButton.setStyleSheet("color:  rgb(170, 173, 9)")
            self.durable_Button(False)
            self.ui.pushButton_2.setEnabled(True)
            self.ui.pushButton_8.setEnabled(False)
            self.ui.pushButton_5.setEnabled(False)

        elif code==2:
            self.MQ_connection_status = False
            self.ui.pushButton.setText('意外断开')
            self.ui.pushButton.setStyleSheet("color:  rgb(170, 173, 9)")
            self.durable_Button(False)
            #self.ui.pushButton_2.setEnabled(True)
            self.ui.pushButton_3.setEnabled(True)
            self.ui.pushButton_8.setEnabled(False)
            self.ui.pushButton_5.setEnabled(False)

        elif code==3:
            self.MQ_connection_status = False
            self.ui.pushButton.setText('连接失败')
            self.ui.pushButton.setStyleSheet("color:  rgb(255, 0, 0)")
            self.durable_Button(False)
            self.ui.pushButton_2.setEnabled(True)
            self.ui.pushButton_8.setEnabled(False)
            self.ui.pushButton_5.setEnabled(False)

        elif code == 4:
            self.MQ_connection_status = False
            self.ui.pushButton.setText(dic_data['msg'])
            self.ui.pushButton.setStyleSheet("color:  rgb(170, 173, 9)")




            # self.durable_Button(False)
            # #self.ui.pushButton_2.setEnabled(True)
            # self.ui.pushButton_3.setEnabled(True)
            # self.ui.pushButton_8.setEnabled(False)
            # self.ui.pushButton_5.setEnabled(False)


    def mq_connect_execute(self): #连接mqtt


        self.ui.pushButton.setText('连接中')
        self.ui.pushButton.setStyleSheet("color:  rgb(170, 173, 9)")

        self.ui.pushButton_2.setEnabled(False)
        server_address=self.ui.lineEdit.text()
        self.config_info['Mq_address']=server_address

        client_ID = self.ui.lineEdit_2.text()
        #self.config_info['Mq_client_id']=client_ID

        name_mqtt=self.ui.lineEdit_6.text()
        self.config_info['Mq_name']=name_mqtt

        pwd_mqtt = self.ui.lineEdit_7.text()
        self.config_info['Mq_pwd']=pwd_mqtt

        self.config_info['Mq_topic'] = self.ui.lineEdit_4.text()




        #self.config_info = YAMLHandler.read_yaml(all_path.configPath)
        YAMLHandler.write_yaml(all_path.configPath, self.config_info) # 保存到配置文件中





        # mgs.log(self.ui.textEdit_2,server_address,mmodule=self.module_name)
        # mgs.log(self.ui.textEdit_2,client_ID,mmodule=self.module_name)
        Logger.info(server_address)
        #topic,
        Logger.info(client_ID)
        self.ui.pushButton_3.setEnabled(True)




        try:
            broker_address, broker_port=server_address.split(':')
        except:
            broker_address, broker_port = server_address,1883

        self.MqttReceive_thread=MqttReceive(broker_address,broker_port,client_ID,name_mqtt,pwd_mqtt)

        # 创建并启动线程，并传递参数
        self.MqttReceive_thread.mqtt_receive_connect_status.connect(self.mqtt_connect_status)  ##触发自定义执行完成信号槽函数
        self.MqttReceive_thread.start()


    def mq_send_execute(self): #发送消息

        mq_send_input_box_check=True

        textEdit_3 = self.ui.textEdit_3.toPlainText()
        #Logger.info(textEdit_3)
        topic=self.ui.lineEdit_3.text()
        if topic =='':
            mq_send_input_box_check = False
            mgs.message(QtWidgets,'MQ', '发布消息主题不能为空！！', fun='about')
        if textEdit_3=='':
            mq_send_input_box_check = False
            mgs.message(QtWidgets,'MQ', '发布消息不能为空！！', fun='about')

        if mq_send_input_box_check:
            self.MqttReceive_thread.seed_info(topic,textEdit_3)
            #Logger.info(f"发送消息:[{topic}]-{textEdit_3}")

        self.config_info['RX_topic'] = self.ui.lineEdit_3.text()

        # self.config_info = YAMLHandler.read_yaml(all_path.configPath)
        YAMLHandler.write_yaml(all_path.configPath, self.config_info)  # 保存到配置文件中

    def mq_close_execute(self): #mq_close_execute  #断开连接
        #self.ui.pushButton_3.setEnabled(False)
        self.MqttReceive_thread.startup_status=False
        try:
            self.SerSta_thread.serial_port_status=False
        except:
            pass
        Logger.info("断开连接……")


    def mq_receive_execute(self): #mq_close_execute 订阅消息

        self.MqttReceive_thread.receive_topic = self.ui.lineEdit_4.text()  # 接收消息主题
        self.MqttReceive_thread.receive_message_box = self.ui.textEdit_2  # 接收消息输入框

        if self.ui.lineEdit_4.text()!='':

            self.MqttReceive_thread.subscribe_receive_msg()
            self.ui.pushButton_5.setEnabled(True)
            self.ui.pushButton_6.setEnabled(False)

            self.config_info['Mq_topic'] = self.ui.lineEdit_4.text()

            YAMLHandler.write_yaml(all_path.configPath, self.config_info)  # 保存到配置文件中

        else:
            mgs.message(QtWidgets,'MQ', '订阅主题不能为空！！', fun='about')




    def mq_unsubscribe_execute(self): #取消订阅
        self.ui.pushButton_5.setEnabled(False)
        textEdit_2 = self.ui.textEdit_2
        # Logger.info(textEdit_3)
        topic=self.ui.lineEdit_4.text()
        self.MqttReceive_thread.unsubscribe_receive_msg(topic)
        self.ui.pushButton_6.setEnabled(True)


    def mq_clean_up_execute(self): #删除消息框
        #self.ui.textEdit_2.setPlainText("")
        self.ui.textEdit_2.clear()



    def mq_clean_up_textEdit_3execute(self): #清除发送输入框
        #self.ui.textEdit_2.setPlainText("")
        self.ui.textEdit_3.clear()



    def serial_connect_status(self,msg):
        if msg == 0:
            self.ui.pushButton_8.setEnabled(True)

        elif msg == 1:
            self.ui.pushButton_7.setEnabled(True)
            self.ui.pushButton_8.setEnabled(False)

    def send_serial_data(self,msg):
        if self.MQ_connection_status:
            topic=self.ui.lineEdit_5.text()
            self.MqttReceive_thread.seed_info(topic,msg)
            #Logger.info(f"发送消息:[{topic}]-{msg}")





    def open_serial_port_execute(self): #开启串口

        topic = self.ui.lineEdit_5.text()
        if topic!="":
            self.ui.pushButton_7.setEnabled(False)

            prot_name = self.combo_ports_name.currentText() #获取端口名称
            BAUD = self.combo_BAUD.currentText()  # 获取波特率
            Logger.info(prot_name)
            Logger.info(BAUD)
            from SerialPort.serial_port import SerialStart
            #
            self.SerSta_thread=SerialStart(prot_name,BAUD)
            self.SerSta_thread.serial_connect_status.connect(self.serial_connect_status)  ##触发自定义执行完成信号槽函数
            self.SerSta_thread.serial_data.connect(self.send_serial_data)  ##触发自定义执行完成信号槽函数
            self.SerSta_thread.start()
            Logger.info('开启端口……')
            self.config_info['TX_topic'] = self.ui.lineEdit_5.text()
            YAMLHandler.write_yaml(all_path.configPath, self.config_info)  # 保存到配置文件中
        else:
            mgs.message(QtWidgets,'MQ', '串口消息发布主题不能为空！！', fun='about')





    def close_serial_port_execute(self):
        self.ui.pushButton_8.setEnabled(False)
        self.SerSta_thread.serial_port_status=False

        Logger.info('关闭端口……')

